package service

import (
	"demo/models"
	"demo/models/response"
	"errors"
	"strings"
)

type DeptService struct{}

// GetAll 查询所有部门信息
func (d *DeptService) GetAll() []models.Dept {
	var depts []models.Dept
	DB.Find(&depts)
	return depts

}

// GetDeptListByPage 分页查询部门信息
func (d *DeptService) GetDeptListByPage(page int, size int) (response.Page, error) {
	var depts []models.Dept
	var total int64
	err := DB.Model(&models.Dept{}).Count(&total)
	err = DB.Find(&depts).Offset((page - 1) * size).Limit(size)
	if err.Error != nil {
		//fmt.Println(err)
		return response.Page{}, errors.New("查询部门信息失败")
	}
	return response.Page{CurrentPage: page, PageSize: size, TotalCount: int(total), TotalPage: int(total) / size, Data: depts}, nil
}

func (d *DeptService) GetDeptById(param string) (models.Dept, error) {
	dept := models.Dept{}
	err := DB.Where("id=?", param).First(&dept)
	if err.Error != nil {
		return dept, errors.New("查询部门信息失败")
	}
	return dept, nil

}

func (d *DeptService) DeleteDeptById(param string) error {
	err := DB.Where("id=?", param).Delete(&models.Dept{})
	if err.Error != nil {
		return errors.New("删除部门信息失败")
	}
	return nil

}

func (d *DeptService) DeleteBatchDeptById(param string) error {
	split := strings.Split(param, ",")
	tx := DB.Where("id in (?)", split).Delete(&models.Dept{})
	if tx.Error != nil {
		return errors.New("批量删除部门信息失败")
	}
	return nil
}
